<script setup>
import {onMounted, ref} from 'vue';
import {useSignStore} from '@/stores/user/sign';
import {ElForm, ElMessage, ElRadio, ElRadioGroup, ElButton, ElInput, ElFormItem} from 'element-plus';
import {Location} from '@element-plus/icons-vue';
import {getAddress} from '@/utils/addressComponent';

const signStore = useSignStore();
const loading = ref(false);
const locationLoading = ref(false);
const verificationCode = ref(''); // 用于存储后端返回的验证码
const signData = ref({
  username: '',
  status: '',
  address: '',
  verificationCode: '',
});

const signForm = ref(null);

onMounted(() => {
  generateVerificationCode();
});

const generateVerificationCode = async () => {
  loading.value = true;
  try {
    const code = await signStore.generateVerificationCode();
    verificationCode.value = code;
    if (!code) {
      ElMessage.error('获取验证码失败，请稍后重试！');
    }
  } catch (error) {
    ElMessage.error('获取验证码失败，请稍后重试！');
    console.error('获取验证码失败:', error);
  } finally {
    loading.value = false;
  }
};

const getLocation = () => {
  locationLoading.value = true;
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(
        async (position) => {
          const latitude = position.coords.latitude;
          const longitude = position.coords.longitude;
          try {
            signData.value.address = await getAddress(latitude, longitude);
          } catch (error) {
            ElMessage.error('获取地址失败：' + error);
          } finally {
            locationLoading.value = false;
          }
        },
        (error) => {
          locationLoading.value = false;
          ElMessage.error('获取地理位置失败，请检查是否开启定位权限。');
          console.error('获取地理位置失败:', error);
        }
    );
  } else {
    locationLoading.value = false;
    ElMessage.error('你的浏览器不支持地理定位。');
  }
};

const submitSign = async () => {
  try {
    loading.value = true;
    if (!signData.value.username || !signData.value.status || !signData.value.address || !signData.value.verificationCode) {
      ElMessage.warning('请填写完整信息！');
      return;
    }

    const success = await signStore.signIn(signData.value);
    if (success) {
      ElMessage.success('签到成功！');
      signData.value = {
        username: '',
        status: '',
        address: '',
        verificationCode: '',
      };
      await generateVerificationCode();
    } else {
      ElMessage.error('签到失败，请检查信息。');
    }
  } catch (error) {
    ElMessage.error('签到过程中发生错误，请稍后重试！');
    console.error('签到失败:', error);
  } finally {
    loading.value = false;
  }
};
</script>

<template>
  <div class="sign-container">
    <div class="sign-card">
      <h2>实验室考勤表</h2>
      <p class="work-time">实验室工作时间: 10:00-12:00, 14:30-17:30, 19:00-21:00</p>

      <el-form ref="signForm" :model="signData" label-width="100px" style=" margin-left:100px;">
        <el-form-item label="学生姓名" required>
          <el-input v-model="signData.username" placeholder="请输入姓名" style="width: 200px;"/>
        </el-form-item>

        <el-form-item label="上班/下班" required>
          <el-radio-group v-model="signData.status">
            <el-radio :label="'上班'">上班</el-radio>
            <el-radio :label="'下班'">下班</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="打卡地址" required>
          <div class="location-container">
            <el-button type="primary" @click="getLocation" :disabled="locationLoading">
              <el-icon>
                <Location/>
              </el-icon>
              {{ locationLoading ? '定位中...' : '点击自动定位' }}
            </el-button>
            <p v-if="signData.address" class="address-text">{{ signData.address }}</p>
            <p v-else class="address-text hint-text">请点击按钮获取地址</p>
          </div>
        </el-form-item>

        <el-form-item label="验证码" required>
          <div class="verification-container">
            <el-input v-model="signData.verificationCode" placeholder="请输入验证码"
                      style="width: 200px; margin-right: 20px"/>
            <el-button type="info" @click="generateVerificationCode" :loading="loading" :disabled="loading">
              刷新验证码
            </el-button>
          </div>
          <div v-if="verificationCode" class="verification-code-display">
            验证码：{{ verificationCode }}
          </div>
        </el-form-item>

        <el-form-item>
          <el-button type="danger" @click="submitSign" :loading="loading" :disabled="loading">
            {{ loading ? '提交中...' : '提交' }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<style>
.sign-container {
  display: flex;
  justify-content: center;
  align-items: center;
  /*
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  */
  height: 100%;
  position: relative;
  overflow: hidden;
}

.sign-container::before {
  content: '';
  position: absolute;
  width: 200%;
  height: 200%;
  background: radial-gradient(circle, rgba(255, 255, 255, 0.1) 20%, transparent 20%);
  background-size: 30px 30px;
  animation: float 10s linear infinite;
}

@keyframes float {
  100% {
    transform: translate(-15px, -15px);
  }
}

.sign-card {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  box-shadow: 0 12px 30px rgba(0, 0, 0, 0.15);
  padding: 40px 50px;
  width: 600px;
  position: relative;
  z-index: 1;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.3);
}

h2 {
  font-size: 32px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 25px;
  position: relative;
  display: inline-block;

}

h2::after {
  content: '';
  position: absolute;
  bottom: -8px;
  left: 50%;
  transform: translateX(-50%);
  width: 60px;
  height: 4px;
  background: linear-gradient(45deg, #409eff, #64b5f6);
  border-radius: 2px;
  animation: underline 2s ease-in-out infinite;
}

@keyframes underline {
  0%, 100% {
    width: 60px;
  }
  50% {
    width: 100px;
  }
}

.work-time {
  color: #5e6d82;
  font-size: 15px;
  margin-bottom: 30px;
  padding: 12px 20px;
  background: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #409eff;
}

.el-form-item {
  margin-bottom: 28px;
}

.el-form-item:last-child {
  margin-bottom: 0;
}

.location-container {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.el-button--primary {
  background: linear-gradient(45deg, #409eff, #64b5f6);
  border: none;
  transition: all 0.3s ease;
}

.el-button--primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(64, 158, 255, 0.3);
}

.address-text {
  background: #f8f9fa;
  padding: 12px;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  width: 100%;
  transition: border-color 0.3s;
}


.verification-container {
  display: flex;
  align-items: center;
  gap: 15px;
}

.verification-code-display {
  padding: 10px 15px;
  background: #ecf5ff;
  color: #409eff;
  border-radius: 6px;
  font-family: monospace;
  letter-spacing: 2px;
  border: 1px dashed #409eff;
  margin-top: 20px;
}

.el-button--danger {
  background: linear-gradient(45deg, #ff6b6b, #ff8787);
  border: none;
  padding: 12px 30px;
  transition: all 0.3s ease;
}

.el-button--danger:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(255, 107, 107, 0.3);
}

.el-input :deep(.el-input__inner) {
  transition: all 0.3s ease;
  border-radius: 8px;
  padding: 12px 15px;
}

.el-input :deep(.el-input__inner:focus) {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.el-radio :deep(.el-radio__input.is-checked + .el-radio__label) {
  color: #409eff;
}

.el-radio :deep(.el-radio__inner) {
  transition: all 0.3s ease;
}

.el-radio :deep(.el-radio__inner:hover) {
  border-color: #409eff;
}

.hint-text {
  color: #a0a8b3;
  font-style: italic;
}
</style>